import { Button, message, Modal } from 'antd';
import React, { useState, useRef, useEffect,useContext } from 'react';
import ProTable from '@ant-design/pro-table';
import AddForm from './components/AddForm';
import { addPermit, removePermit, getList, getGroupList } from './service';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { UserContext } from '@/layouts/UserProvider';

const TableList = () => {
  const [groupEnum, setGroupEnumList] = useState();
  const [updateModalVisible, handleDetailModalVisible] = useState(false);
  const actionRef = useRef();
  const userCtx = useContext(UserContext);
  const permits=userCtx.userPermits;
  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');
    try {
      await addPermit({
        ...fields,
        type: parseInt(fields.type)
      }).then((data)=>{
        hide();
        if(data.code=='200'){
          message.success('添加成功');
          handleDetailModalVisible(false);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }else{
          message.error(data.msg);
        }
      })
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
    }
  };
  useEffect(() => {
    getGroupList().then((data) => {
      let result = data?.data || [];
      let list = {};
      if(result && result.length>0){
        result.forEach((item, i) => {
          list[item.group] = { text: item.group, status: item.group };
        });
        setGroupEnumList(list);
      }
    });
  }, []);
  const handleDelPermits = (record) => {
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      content: '是否要删除？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        removePermit(record).then(()=>{
          if (actionRef.current) {
            actionRef.current.reload();
          }
        })

      },
    });
  };
  const columns = [
    {
      title: '所属部门',
      dataIndex: 'group',
      hideInForm: true,
      valueEnum: groupEnum,
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '创建时间',
      search: false,
      dataIndex: 'create_time',
    },
    {
      title: '所属用户',
      search: false,
      dataIndex: 'type',
      valueEnum: {
        1:{text:'管理员用户'},
        2:{text:'基础用户'},
        3:{text:'普通用户'},
        4:{text:'超级管理员用户'},
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) =>{
        let res=[];
        if(permits.includes('deleteUser')){
            res.push(<Button size="small" key="detail" onClick={() => handleDelPermits(record)}>
            删除
          </Button>)
        }
        return res;
        
      },
    },
  ];
  return (
    <>
      <ProTable
        actionRef={actionRef}
        rowKey="key"
        search={{
          collapsed: false,
          defaultCollapsed: false,
          collapseRender: () => '',
          labelWidth: 120,
          searchText: '搜索',
        }}
        request={async (params, sorter, filter) => {
          try{
            params.type = 4;
            params.is_total=true;
            params.limit=params.pageSize;
            params.offset=(params.current-1)*params.pageSize;
            let res = await getList({ ...params, sorter, filter });
            if (res.data == null && res.total != 0) {
              params.current = params.current - 1;
              params.offset = (params.current - 1) * params.pageSize;
              res = await getList({ ...params, sorter, filter });
            }
            return {data: JSON.stringify(res.data) != '{}'?res.data:[], success: true, total: res.total || 0}
          }catch(error){
            return { data: [], success: false, total: 0}
          }
        }}
        columns={columns}
        toolBarRender={() => {
          let res=[];
          if(permits.includes('addUser')){
              res.push( <Button type="primary" key="primary" onClick={() => handleDetailModalVisible(true)}>
              添加用户权限
            </Button>)
          }
          return res;
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          hideOnSinglePage: false,
          showTotal: (total) => `共有 ${total} 条记录`,
          pageSize:10,
        }}
      />
      <AddForm
        onSubmit={async (value) => {
          await handleAdd(value);
        }}
        onCancel={() => {
          handleDetailModalVisible(false);
        }}
        updateModalVisible={updateModalVisible}
      />
    </>
  );
};

export default TableList;
